<template>
  <QDialog v-model="show" persistent>
    <t-card v-recursionRemoveTabindex class="mixview-container" style="width: 60vw; max-width: 977px; overflow: hidden;">
      <div class="padding-16-24" style='line-height:16px; background-color: transparent;display: flex; justify-content: space-between;'>
        <div class="titleColor">{{ Term.title.setChart }}</div>
        <t-button dense flat icon="fas dx-icon icon-t-delete-01" style="padding:0px;min-width: auto;" v-close-popup>
        </t-button>
      </div>
      <t-separator color="#F0F2F5" />
      <div class="row context">
        <div class="col col-xs-12 col-sm-12 col-md-4 col-lg-3 col-xl-3 padding-16-24">
          <div style="">
            <div class='padding-b24 titleColor'>{{Term.title.chartType}}</div>
            <t-list :bordered="false" class="chartType">
              <t-item
                @click="() => { onClickTag(item) }"
                clickable
                class="skipRemoveTabindex"
                v-for="item in chartType"
                :active="item.Tag == instance.ChartType"
              >
                <t-item-section><div class="chartTypeitem"><t-icon :name="item.icon" style="padding-right: 8px;"/> {{ item.name }}</div></t-item-section>
              </t-item>
            </t-list>
          </div>
        </div>
        <div class="col col-xs-12 col-sm-12 col-md-8 col-lg-5 col-xl-5 padding-16-24 border-lr ">
          <div>
            <div class='padding-b24 titleColor'>{{Term.title.configuration}}</div>
          </div>
          <div class="column" style="row-gap:24px">
            <div class="">
              <!-- 名称 -->
              <TInput
                ref="refChartName"
                tabindex="0"
                :label="Term.title.name"
                borderType="borderless"
                labelPosition="top"
                v-model="instance.ChartName"
                required="true"
                :rules="[val => !!val || '',  (val, rules) => checkExistChartName(val) || (Term.notify.sameChartName||'已存在') ]"
              >
              </TInput>
            </div>
            <div class="">
              <div class="row" style="column-gap: 8px;">
                <div class="col">
                  <!-- 分组依据 -->
                  <t-select
                    v-removeTabindex
                    ref="refGroupColumn"
                    @update:model-value="updateGroupColumn"
                    :label="Term.title.groupBy"
                    borderType="outlined"
                    labelPosition="top"
                    required="true"
                    v-model="instance.GroupColumn"
                    :placeholder="Term.placeholder.groupBy"
                    emit-value
                    map-options
                    del-clearable
                    :use-input="true"
                    itemsDataSourceType='static'
                    :staticItems="groupColumns"
                    :rules="[val => !!val || '']"
                  >
                  </t-select>
                </div>
                <!-- <span class="nbsp">&nbsp;</span> -->
                <div class="col" v-if="aggregationWithDate.length > 0">
                  <t-select
                    label="　"
                    v-removeTabindex
                    ref="refAggDateValue"
                    v-if="aggregationWithDate.length > 0"
                    borderType="outlined"
                    labelPosition="top"
                    v-model="instance.AggDateValue"
                    :placeholder="Term.placeholder.collectionMethod"
                    emit-value
                    map-options
                    del-clearable
                    :use-input="true"
                    itemsDataSourceType='static'
                    :staticItems="aggregationWithDate"
                    :rules="[val => !!val || '']"
                  >
                  </t-select>
                </div>
              </div>
            </div>
            <div class="">
              <!-- 聚合 -->
              <div class="row" style="column-gap: 8px;">
                <div class="col">
                  <t-select
                    v-removeTabindex
                    ref="refAggregation"
                    :label="Term.placeholder.polymerization"
                    borderType="outlined"
                    labelPosition="top"
                    required="true"
                    v-model="instance.Aggregation"
                    :placeholder="Term.placeholder.polymerization"
                    emit-value
                    map-options
                    del-clearable
                    :use-input="true"
                    itemsDataSourceType='static'
                    :staticItems="aggregationDs"
                    :rules="[val => !!val || '']"
                  >
                  </t-select>
                </div>
                <!-- <span class="nbsp">&nbsp;</span> -->
                <div class="col" v-if="instance.Aggregation != 'count'">
                  <t-select
                    label="　"
                    v-removeTabindex
                    ref="refAggregationFiled"
                    v-if="instance.Aggregation != 'count'"
                    borderType="outlined"
                    labelPosition="top"
                    v-model="instance.AggregationFiled"
                    :placeholder="Term.placeholder.polymerizationMethod"
                    emit-value
                    map-options
                    del-clearable
                    :use-input="true"
                    itemsDataSourceType='static'
                    :staticItems="aggregationFiled"
                    :rules="[val => !!val || '']"
                  >
                  </t-select>
                </div>
              </div>
            </div>
            <div class="">
              <div class="row" style="column-gap: 8px;">
                <div class="col">
                  <t-select
                    ref="refSortType"
                    v-removeTabindex
                    :label="Term.title.sort"
                    borderType="outlined"
                    labelPosition="top"
                    required="true"
                    v-model="instance.SortType"
                    :placeholder="Term.placeholder.polymerizationMethod"
                    emit-value
                    map-options
                    del-clearable
                    :use-input="true"
                    itemsDataSourceType='static'
                    :staticItems="sortTypeDs"
                    :rules="[val => !!val || '']"
                  >
                  </t-select>
                </div>
                <!-- <span class="nbsp">&nbsp;</span> -->
                <div class="col">
                  <t-select
                    label="　"
                    v-removeTabindex
                    ref="refDataSort"
                    borderType="outlined"
                    labelPosition="top"
                    v-model="instance.DataSort"
                    :placeholder="Term.placeholder.sortMethod"
                    emit-value
                    map-options
                    del-clearable
                    :use-input="true"
                    itemsDataSourceType='static'
                    :staticItems="dataSortList"
                  >
                  </t-select>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col col-xs-12 col-sm-12 col-md-12 col-lg-4 col-xl-4 padding-16-24 ">
          <div class="" style="">
            <div class="titleColor">{{ Term.title.chart }}</div>
            <div style="position: relative;">
              <div v-show="!instance.GroupColumn" style='position: absolute;height: 100%;width: 100%;display: flex;justify-content: center;align-items: center;z-index: 1;background-color: white;'>
                <NoDataPlaceholder :text="$q.lang?.dataGrid?.emptyText"></NoDataPlaceholder>
              </div>
              <Chart
                :enableNoDataPlaceholder="false"
                height="300px"
                v-bind="vBindChartOpts(instance)"
                :data="chartData"
              />
            </div>
          </div>
        </div>
      </div>
      <t-separator color="#F0F2F5" />
      <div class="padding-16-24 col">
        <div class="row justify-end" style="column-gap: 8px;">
          <t-button
            :label="Term.button.cancel"
            class="tr-button-default"
            v-close-popup
          />
          <t-button
            :label="Term.button.save"
            class="tr-button-primary"
            @click="onConfirm"
          />
        </div>
      </div>
    </t-card>
  </QDialog>
</template>

<script>
import { computed, ref, toRef, nextTick} from 'vue';
import {
  commonProps,
  pickOwnForBasicComponent,
  usePropsTwoWayValues,
} from 't/common/utils';

import Chart from 't/common/chart';

import { vBindChartOpts as vBindChartOptsBase } from './echartConfig';
import { date, debounce, dom, setCssVar, useQuasar } from '@teld/q-components';
import _ from 'lodash';

import TInput from 't/basic/input';
import TSelect from 't/basic/select';
import TButton from 't/basic/button';
import QDialog from '@teld/q-components/Dialog';

import TCard from 't/basic/card';
import TIcon from 't/basic/icon';
import TList from 't/basic/list';
import TItem from 't/basic/item';
import TSeparator from 't/basic/separator';
//import QCard from '@teld/q-components/Card';
//import QBtn from '@teld/q-components/Button';
//import QIcon from '@teld/q-components/Icon';
// import QList, { QItem } from '@teld/q-components/Item';
// import QSeparator from '@teld/q-components/Separator';
import NoDataPlaceholder from 't/bussiness/data-grid/components/no-data-placeholder.vue';
import { useI18n } from 'vue-i18n';
export default {
  directives: {
    removeTabindex: {
      mounted(el) {
        // 移除 tabindex 属性
        el?.removeAttribute('tabindex');
      },
    },
    recursionRemoveTabindex: {
      mounted(el) {
        el?.querySelectorAll("[tabindex]").forEach(item => {
          if (item.classList.contains('skipRemoveTabindex')) {
              return;
          }
          item.removeAttribute('tabindex')
        })
      }
    },
    tTabindex:{
      mounted(el, binding) {
        el?.setAttribute('tabindex', binding.value);
      }
    }
  },
  components: {
    Chart,
    NoDataPlaceholder,
  },
  props: {
    terms: Object,
    show: {
      type: Boolean,
      default() {
        return false;
      },
    },
    instance: {
      type: Object,
    },
    data: {
      type: Array,
      default() {
        return [];
      },
    },
    columns: Array,
    chartList: Array,
  },
  emit: ['confirm'],
  setup(props, { attrs, emit, expose, slots }) {
    const twoWayProps = usePropsTwoWayValues(['show']);
    const $q = useQuasar();
    const { t } = useI18n({ useScope: 'global' });

    const Terms = props.terms;

    let ColGroupMapping = {
      INT: 'Number',
      DECIMAL: 'Number',
      STRING: 'String',
      DATE: 'Date',
      DATETIME: 'DateTime',
    };
    let groupByColumns = _.groupBy(props.columns, item => {
      let UpperCaseDataType = item.dataType.toUpperCase();
      return ColGroupMapping[UpperCaseDataType] || UpperCaseDataType;
    });
    let groupColumns = _.map(props.columns, item => {
      return { value: item.dataField, label: t(item?.ValueInfo_caption?.ReferenceExpr, item.caption) };
    });

    const aggregationFiled = computed(() => {
      let returnValue = _.map(groupByColumns.Number, item => {
        return { value: item.dataField, label: t(item?.ValueInfo_caption?.ReferenceExpr, item.caption) };
      });
      return returnValue;
    });

    const timeGroup = [
      { value: '1', label: Terms?.title?.year },
      { value: '2', label: Terms?.title?.month },
      // { value: "7", label: "按年周" },
      { value: '8', label: Terms?.title?.week },
      { value: '3', label: Terms?.title?.date },
      { value: '4', label: Terms?.title?.hour },
      { value: '5', label: Terms?.title?.minute },
      { value: '6', label: Terms?.title?.second },
    ];
    const dateGroup = [
      { value: '1', label: Terms?.title?.year },
      { value: '2', label: Terms?.title?.month },
      // { value: "7", label: "按年周" },
      { value: '8', label: Terms?.title?.week },
      { value: '3', label: Terms?.title?.date },
    ];

    const mockData = computed(() => {
      debugger;

      return [1,1,1,2,2].map(item=>{
        let o ={};

        if(props.instance && props.instance.GroupColumn){
          o[props.instance.GroupColumn]= `Data${item}`
        }

        if(aggregationWithDate.value.length > 0){
          o[props.instance.GroupColumn]= new Date()
        }

        if(props.instance && props.instance.AggregationFiled){
          o[props.instance.AggregationFiled]= item
        }
        return o
      })
      // return [o];
    });

    const chartData = computed(() => {
      // :data="data.length == 0 ? mockData : data"

      if (props.data.length == 0){
        return mockData.value;
      }else if (props.data.length > 1000) {
        return props.data.slice(0, 1000);
      } else {
        return props.data || [];
      }
    });

    const aggregationWithDate = computed(() => {
      if (
        groupByColumns.Date &&
        _.find(groupByColumns.Date, { dataField: props.instance.GroupColumn })
      ) {
        return dateGroup;
      } else if (
        groupByColumns.DateTime &&
        _.find(groupByColumns.DateTime, {
          dataField: props.instance.GroupColumn,
        })
      ) {
        return timeGroup;
      }
      return [];
    });

    const vBindChartOpts = conf => {
      console.log('vBindChartOpts', conf)
      let ops = vBindChartOptsBase(conf);
      delete ops.option.tooltip;
      ops.option.series.forEach(s => {
        s.label = { show: false }
      })
      return ops;
    };

    const refChartName = ref();
    const refGroupColumn = ref();
    const refAggDateValue = ref();
    const refAggregation = ref();
    const refAggregationFiled = ref();
    const refSortType = ref();
    const refDataSort = ref();

    let autoChartName = `${Terms?.title?.press} ${Terms?.title?.userSelection} ${Terms?.title?.statistics}`

    const setChartName = (val) => {

      if(props.instance.ChartName=="" || autoChartName==props.instance.ChartName){
        let col = _.find(groupColumns,{value: val || props.instance.GroupColumn})
        if(col){
          autoChartName =`${Terms?.title?.press} ${col.label} ${Terms?.title?.statistics}`;
        }
        props.instance.ChartName = autoChartName;
      }
    }
    const onClickTag = (item) => {
      setChartName()
      props.instance.ChartType = item.Tag
    }
    const updateGroupColumn = (val) => {
      setChartName(val);

      nextTick(() => {
          debugger;
          if (aggregationWithDate.value.length > 0) {
              if ("" == props.instance.AggDateValue) {
                  props.instance.AggDateValue = "1"
              }
          } else {
              props.instance.AggDateValue = ""
          }
      })
    }
    const oldChartName = props.instance.ChartName;

    const checkExistChartName = (val) => {
      if (val) {
        let checkExist = props.chartList.find(item => item.ChartName == val && item.ChartName != oldChartName)
        return checkExist ? false : true;
      } else {
       return true
      }
    }

    return {
      oldChartName,
      onClickTag,
      updateGroupColumn,
      refChartName,
      refGroupColumn,
      refAggDateValue,
      refAggregation,
      refAggregationFiled,
      refSortType,
      refDataSort,
      checkExistChartName,
      mockData,
      chartData,
      onConfirm: function () {
        let validate = true;

        debugger;
        if (false == checkExistChartName(props.instance.ChartName)) {
          refChartName.value.validate();
          validate = false;
        }

        if (!props.instance.ChartName) {
          refChartName.value.validate();
          validate = false;
        }

        if (!props.instance.GroupColumn && refGroupColumn.value) {
          refGroupColumn.value.validate();
          validate = false;
        }

        if (!props.instance.AggDateValue && refAggDateValue.value) {
          // validate = validate || refAggDateValue.value.validate();
          refAggDateValue.value.validate();
          validate = false;
        }

        if (!props.instance.Aggregation && refAggregation.value) {
          refAggregation.value.validate();
          validate = false;
        }

        if (!props.instance.AggregationFiled && refAggregationFiled.value) {
          refAggregationFiled.value.validate();
          validate = false;
        }

        if (!props.instance.SortType) {
          validate = validate || refSortType.value.validate();
          validate = false;
        }

        // if (!props.instance.DataSort && refDataSort.value) {
        //   refDataSort.value.validate();
        //   validate = false;
        // }

        if (validate) {
          twoWayProps.show.value = false;
          emit('confirm', props.instance);
        }
      },
      show: twoWayProps.show,
      data: props.data,
      vBindChartOpts,
      Term: Terms,
      // confEchartVisible: true,
      // chartSpan: 4,
      // dragging: false,
      // chartName: ref(''),
      chartType: [
        {
          Tag: 'fas-pie-chart',
          name: Terms?.title?.pieChart,
          icon: 'fas dx-icon icon-t-pie-chart',
        },
        {
          Tag: 'fas-bar-chart',
          name: Terms?.title?.histogram,
          icon: 'fas dx-icon icon-t-bar-chart',
        },
        {
          Tag: 'fas-line-chart',
          name: Terms?.title?.lineChart,
          icon: 'fas dx-icon icon-t-chart-line',
        },
        {
          Tag: 'fas-strip-chart',
          name: Terms?.title?.barChart,
          icon: 'fas iconfont fasfont icon-fasstrip',
        },
        // {
        //   Tag: 'fas-funnel-chart',
        //   name: Terms?.title?.funnelChart,
        //   icon: 'fasfont icon-fasfunnel',
        // },
      ],
      groupColumns: groupColumns,
      groupByColumns: groupByColumns,
      aggregationFiled,
      // groupColumnValue: ref(''),
      aggregationDs: [
        // { value: "", label: "不处理" },
        { value: 'count', label: Terms?.title?.count },
        // { value: "distinctCount", label: "去重计数" },
        { value: 'sum', label: Terms?.title?.sum },
        { value: 'avg', label: Terms?.title?.avg },
        // { value: "max", label: "最大值" },
        // { value: "min", label: "最小值" },
      ],
      // aggregationValue: ref('count'),
      // aggregationFiledValue: ref(''),
      sortTypeDs: [
        { value: 'name', label: Terms?.title?.sortTypeDsName, valueType: 9 },
        { value: 'value', label: Terms?.title?.sortTypeDsValue, valueType: 2 },
      ],
      // sortTypeValue: ref('value'),
      dataSortList: [
        // { value: '', label: Terms?.title?.dataSortList },
        { value: '1', label: Terms?.title?.dataSortListAsc },
        { value: '-1', label: Terms?.title?.dataSortListDes },
      ],
      // dataSortValue: ref(''),
      // selectedItemKeys: ref([]),
      // aggregationWithDateValue: ref(''),
      timeGroup,
      dateGroup,
      aggregationWithDate,
      dataSource: [],
      fullChart: false,
    };
  },
};
</script>

<style lang="scss">
  .mixview-container{
    font-size: 16px;
  }
  .mixview-container .padding-16-24{
    padding: 16px 24px;
  }
  .mixview-container .padding-b24{
    padding-bottom: 24px;
  }
  .mixview-container .context{
    .border-lr{
      border-left: 1px solid #F0F2F5;
      border-right: 1px solid #F0F2F5;
    }

    .nbsp{
      width: 8px;
    }

    .chartType {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.56);
      .q-item--active{
        background-color:var(--t-color-selected) ;
      }

      & .q-item{
        border-bottom: 1px solid #F0F2F5;

        &:last-child{
          border-bottom-width: 0px;
        }
      }
    }
  }
  .mixview-container .titleColor{
    color: rgba(0,0,0, var(--t-color-opacity, /*批量处理90%透明度*/0.9));
  }
</style>
